﻿using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text.RegularExpressions;

namespace FrameworkEditor
{
	internal class SubAllToOne : IAbSetting
	{
		private Regex _ignoreRegex;
		internal SubAllToOne(string path, string needRegexCfg, string ignoreRegexCfg) : base(path, needRegexCfg)
		{
			if (!string.IsNullOrEmpty(ignoreRegexCfg))
			{
				_ignoreRegex = new Regex(ignoreRegexCfg);
			}
		}

		internal override List<AssetBundleBuild> GetAllBuilders()
		{
			List<AssetBundleBuild> ret = new List<AssetBundleBuild>();
			if (string.IsNullOrEmpty(DirPath))
			{
				return ret;
			}

			if (!Directory.Exists(DirPath))
			{
				Debug.LogWarning("SubAllToOne.GetAllBuilders, DirPath = " + DirPath + " is not exists!");
				return ret;
			}
			
			List<string> assetNames = new List<string>();

			foreach (var directory in Directory.GetDirectories(DirPath, "*.*", SearchOption.TopDirectoryOnly))
			{
				string abName = EditorUtils.GetRelativePathToDir(directory, EditorUtils.assetRootDir);
				if (null != _ignoreRegex && _ignoreRegex.IsMatch(abName))
				{
					continue;
				}
				foreach (string file in Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories))
				{
					if (!IsNeedBuild(file))
					{
						continue;
					}
					string assetPath = EditorUtils.GetPathRelativeToAssets(file);
					//Debug.Log("abName = " + abName + " assetPath = " + assetPath);
					assetNames.Add(assetPath);
				}
				//Debug.Log("abName = " + abName + " directory = " + directory + " EditorUtils.assetRootDir = " + EditorUtils.assetRootDir);
				ret.Add(new AssetBundleBuild()
				{
					assetBundleName = abName + Framework.FrameworkSettings.AssetBundleExt,
					assetNames = assetNames.ToArray(),
				});
				assetNames.Clear();
			}
			return ret;
		}
	}
}